package com.blog.blog.controller;

import com.blog.blog.common.ApiBaseResponse;
import com.blog.blog.dto.LoginDTO;
import com.blog.blog.dto.RegisterDTO;
import com.blog.blog.service.AuthService;
import com.blog.blog.mapper.UserMapper;
import com.blog.blog.po.UserPO;
import com.blog.blog.vo.UserProfileVO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.PutMapping;

import java.util.HashMap;
import java.util.Map;

import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "用户认证", description = "用户登录、注册、个人信息管理等接口")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;
    private final UserMapper userMapper;

    public AuthController(AuthService authService, UserMapper userMapper) {
        this.authService = authService;
        this.userMapper = userMapper;
    }

    @PostMapping("/login")
    public ApiBaseResponse<Map<String, Object>> login(@RequestBody LoginDTO dto) {
        String token = authService.login(dto.getUsername(), dto.getPassword());
        if (token == null) {
            return ApiBaseResponse.error(401, "用户名或密码错误");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        return ApiBaseResponse.success(data);
    }

    @PostMapping("/logout")
    public ApiBaseResponse<Boolean> logout(@RequestHeader(value = "Authorization", required = false) String authorization) {
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            authService.logout(token);
        }
        return ApiBaseResponse.success(Boolean.TRUE);
    }

    @GetMapping("/profile")
    public ApiBaseResponse<UserProfileVO> profile(@RequestHeader(value = "Authorization", required = false) String authorization) {
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return ApiBaseResponse.error(401, "未授权");
        }
        String token = authorization.substring(7);
        Long userId = authService.verify(token);
        if (userId == null) {
            return ApiBaseResponse.error(401, "未授权");
        }
        UserPO user = userMapper.selectById(userId);
        if (user == null) {
            return ApiBaseResponse.error(404, "用户不存在");
        }
        String roles = userMapper.selectRolesByUserId(userId);
        String perms = userMapper.selectPermsByUserId(userId);
        UserProfileVO vo = new UserProfileVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setNickname(user.getNickname());
        vo.setAvatar(user.getAvatar());
        vo.setEmail(user.getEmail());
        vo.setRoles(roles);
        vo.setPerms(perms);
        return ApiBaseResponse.success(vo);
    }

    @PostMapping("/register")
    public ApiBaseResponse<Boolean> register(@RequestBody RegisterDTO dto) {
        boolean ok = authService.register(dto);
        return ok ? ApiBaseResponse.success(Boolean.TRUE) : ApiBaseResponse.error(400, "注册失败");
    }

    @PutMapping("/profile/nickname")
    public ApiBaseResponse<Boolean> updateNickname(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                   @RequestBody com.blog.blog.dto.UpdateNicknameDTO dto) {
        Long userId = extractUserId(authorization);
        if (userId == null) return ApiBaseResponse.error(401, "未授权");
        if (dto == null || dto.getNickname() == null || dto.getNickname().isBlank()) return ApiBaseResponse.error(400, "昵称不能为空");
        int n = userMapper.updateNickname(userId, dto.getNickname());
        return ApiBaseResponse.success(n > 0);
    }

    @PutMapping("/profile/password")
    public ApiBaseResponse<Boolean> updatePassword(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                   @RequestBody com.blog.blog.
                                                       dto.UpdatePasswordDTO dto) {
        Long userId = extractUserId(authorization);
        if (userId == null) return ApiBaseResponse.error(401, "未授权");
        if (dto == null || dto.getNewPassword() == null || dto.getNewPassword().isBlank()) return ApiBaseResponse.error(400, "新密码不能为空");
        if (dto.getOldPassword() == null || dto.getOldPassword().isBlank()) return ApiBaseResponse.error(400, "原密码不能为空");
        com.blog.blog.po.UserPO u = userMapper.selectById(userId);
        org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder encoder = new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder();
        if (u == null) return ApiBaseResponse.error(404, "用户不存在");
        boolean ok = false;
        if (u.getPassword() != null && encoder.matches(dto.getOldPassword(), u.getPassword())) {
            ok = true;
        } else {
            // 开发环境兜底：兼容 admin/admin 登录后的修改密码
            if (u.getUsername() != null && u.getUsername().equals("admin") && "admin".equals(dto.getOldPassword())) {
                ok = true;
            }
        }
        if (!ok) return ApiBaseResponse.error(400, "原密码不正确");
        int n = userMapper.updatePassword(userId, encoder.encode(dto.getNewPassword()));
        return ApiBaseResponse.success(n > 0);
    }

    @PutMapping("/profile/avatar")
    public ApiBaseResponse<Boolean> updateAvatar(@RequestHeader(value = "Authorization", required = false) String authorization,
                                                 @RequestBody com.blog.blog.dto.UpdateAvatarDTO dto) {
        Long userId = extractUserId(authorization);
        if (userId == null) return ApiBaseResponse.error(401, "未授权");
        if (dto == null || dto.getAvatar() == null || dto.getAvatar().isBlank()) return ApiBaseResponse.error(400, "头像不能为空");
        int n = userMapper.updateAvatar(userId, dto.getAvatar());
        return ApiBaseResponse.success(n > 0);
    }

    private Long extractUserId(String authorization) {
        if (authorization == null || !authorization.startsWith("Bearer ")) return null;
        String token = authorization.substring(7);
        return authService.verify(token);
    }
}


